package com.example.securtydemo.config;

import com.example.securtydemo.permission.bean.Role;
import com.example.securtydemo.permission.bean.UserInfo;
import com.example.securtydemo.permission.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
          1 通过username获取到userInfo信息
          2 通过User(username,password,authorities)返回UserDetails
         */
        UserInfo userInfo = userInfoService.findByusername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("NOT FOUND");
        }
        // 定义权限列表
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        // 用户拥有的权限
        for (Role role : userInfo.getRoles()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        User userDetails = new User(userInfo.getUsername(), userInfo.getPassword(), authorities);
        return userDetails;
    }
}
